<template>
  <div class="chat-box">
    <div class="chat-header">
      <h3>{{ title || '健康顾问AI助手' }}</h3>
      <div class="header-actions" v-if="conversationId">
        <el-button size="small" icon="Edit" @click="showEditTitleDialog = true"></el-button>
        <el-button size="small" icon="Delete" @click="confirmDelete"></el-button>
      </div>
    </div>
    
    <div class="chat-messages" ref="messagesContainer">
      <div v-if="messages.length === 0" class="welcome-message">
        <div class="welcome-content">
          <h3>欢迎使用健康顾问AI助手</h3>
          <p>您可以向我咨询任何健康相关的问题，例如：</p>
          <ul>
            <li>健康饮食的建议</li>
            <li>运动锻炼的方法</li>
            <li>常见疾病的症状</li>
            <li>健康生活方式的养成</li>
          </ul>
        </div>
      </div>
      
      <div 
        v-for="(msg, index) in messages" 
        :key="index" 
        :class="['message', msg.role === 'user' ? 'user-message' : 'ai-message']"
      >
        <div class="message-avatar">
          <el-avatar :icon="msg.role === 'user' ? 'User' : 'ChatDotRound'" :size="36"></el-avatar>
        </div>
        <div class="message-content">
          <p v-html="formatMessage(msg.content)"></p>
        </div>
      </div>
      
      <div v-if="loading" class="message ai-message">
        <div class="message-avatar">
          <el-avatar icon="ChatDotRound" :size="36"></el-avatar>
        </div>
        <div class="message-content">
          <p><span class="typing-indicator">思考中...</span></p>
        </div>
      </div>
    </div>
    
    <div class="chat-input">
      <el-input
        v-model="userInput"
        type="textarea"
        :rows="2"
        placeholder="输入您的问题..."
        @keydown.enter.exact.prevent="sendMessage"
        :disabled="loading"
      />
      <el-button 
        type="primary" 
        :disabled="loading || !userInput.trim()" 
        @click="sendMessage"
        icon="Position"
      >发送</el-button>
    </div>
    
    <!-- 编辑对话标题对话框 -->
    <el-dialog
      v-model="showEditTitleDialog"
      title="编辑对话标题"
      width="30%"
    >
      <el-input v-model="newTitle" placeholder="请输入新标题"></el-input>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showEditTitleDialog = false">取消</el-button>
          <el-button type="primary" @click="updateTitle">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, nextTick, watch } from 'vue';
import aiService from '@/services/aiService';
import { ElMessage, ElMessageBox } from 'element-plus';

export default {
  name: 'ChatBox',
  props: {
    conversationId: {
      type: [Number, String],
      default: null
    },
    title: {
      type: String,
      default: ''
    }
  },
  emits: ['conversation-deleted', 'title-updated'],
  setup(props, { emit }) {
    const userInput = ref('');
    const messages = ref([]);
    const loading = ref(false);
    const messagesContainer = ref(null);
    const showEditTitleDialog = ref(false);
    const newTitle = ref('');
    
    const formatMessage = (content) => {
      return content
        .replace(/\n/g, '<br>')
        .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
        .replace(/\*(.*?)\*/g, '<em>$1</em>')
        .replace(/```([\s\S]*?)```/g, '<pre><code>$1</code></pre>');
    };
    
    const scrollToBottom = () => {
      nextTick(() => {
        if (messagesContainer.value) {
          messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
        }
      });
    };
    
    const loadMessages = async () => {
      if (!props.conversationId) return;
      
      try {
        loading.value = true;
        const response = await aiService.getConversationMessages(props.conversationId);
        messages.value = response.data.data;
        scrollToBottom();
      } catch (error) {
        ElMessage.error('加载对话消息失败');
        console.error('加载消息错误:', error);
      } finally {
        loading.value = false;
      }
    };
    
    const sendMessage = async () => {
      if (!userInput.value.trim() || loading.value) return;
      
      const message = userInput.value;
      userInput.value = '';
      
      // 先添加用户消息
      messages.value.push({
        role: 'user',
        content: message,
        timestamp: new Date().toISOString()
      });
      
      scrollToBottom();
      
      try {
        loading.value = true;
        const response = await aiService.sendMessage(message, props.conversationId);
        const { reply, conversationId } = response.data.data;
        
        // 如果是新对话，更新URL
        if (!props.conversationId && conversationId) {
          emit('conversation-created', conversationId);
        }
        
        // 添加AI回复
        messages.value.push({
          role: 'assistant',
          content: reply,
          timestamp: new Date().toISOString()
        });
        
        scrollToBottom();
      } catch (error) {
        ElMessage.error('发送消息失败');
        console.error('发送消息错误:', error);
      } finally {
        loading.value = false;
      }
    };
    
    const confirmDelete = () => {
      ElMessageBox.confirm(
        '确定要删除此对话吗？',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
        .then(() => {
          deleteConversation();
        })
        .catch(() => {});
    };
    
    const deleteConversation = async () => {
      try {
        await aiService.deleteConversation(props.conversationId);
        ElMessage.success('对话已删除');
        emit('conversation-deleted');
      } catch (error) {
        ElMessage.error('删除对话失败');
        console.error('删除对话错误:', error);
      }
    };
    
    const updateTitle = async () => {
      if (!newTitle.value.trim()) {
        ElMessage.warning('标题不能为空');
        return;
      }
      
      try {
        await aiService.updateConversationTitle(props.conversationId, newTitle.value);
        ElMessage.success('标题已更新');
        emit('title-updated', newTitle.value);
        showEditTitleDialog.value = false;
      } catch (error) {
        ElMessage.error('更新标题失败');
        console.error('更新标题错误:', error);
      }
    };
    
    watch(() => props.conversationId, () => {
      if (props.conversationId) {
        loadMessages();
      } else {
        messages.value = [];
      }
    }, { immediate: true });
    
    watch(() => props.title, () => {
      newTitle.value = props.title;
    }, { immediate: true });
    
    onMounted(() => {
      if (props.conversationId) {
        loadMessages();
      }
    });
    
    return {
      userInput,
      messages,
      loading,
      messagesContainer,
      showEditTitleDialog,
      newTitle,
      formatMessage,
      sendMessage,
      confirmDelete,
      updateTitle
    };
  }
};
</script>

<style scoped>
.chat-box {
  display: flex;
  flex-direction: column;
  height: 100%;
  border-radius: 8px;
  overflow: hidden;
  background-color: #f9f9f9;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background-color: #4a7bff;
  color: white;
}

.chat-header h3 {
  margin: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.chat-messages {
  flex-grow: 1;
  padding: 16px;
  overflow-y: auto;
  background-color: #f5f7fa;
}

.welcome-message {
  display: flex;
  justify-content: center;
  padding: 40px 0;
}

.welcome-content {
  max-width: 600px;
  background-color: white;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.welcome-content h3 {
  margin-top: 0;
  color: #4a7bff;
}

.welcome-content ul {
  padding-left: 20px;
}

.message {
  display: flex;
  margin-bottom: 16px;
}

.user-message {
  flex-direction: row-reverse;
}

.message-avatar {
  margin: 0 8px;
}

.message-content {
  max-width: 70%;
  padding: 12px 16px;
  border-radius: 8px;
  overflow-wrap: break-word;
}

.user-message .message-content {
  background-color: #4a7bff;
  color: white;
  border-top-right-radius: 0;
}

.ai-message .message-content {
  background-color: white;
  border-top-left-radius: 0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.typing-indicator {
  display: inline-block;
  position: relative;
}

.typing-indicator::after {
  content: '...';
  position: absolute;
  animation: typingDots 1.5s infinite;
}

@keyframes typingDots {
  0% { content: '.'; }
  33% { content: '..'; }
  66% { content: '...'; }
}

.chat-input {
  display: flex;
  padding: 16px;
  background-color: white;
  border-top: 1px solid #e0e0e0;
}

.chat-input .el-input {
  margin-right: 12px;
}

pre {
  background-color: #f0f0f0;
  padding: 8px;
  border-radius: 4px;
  overflow-x: auto;
}

.message-content :deep(code) {
  font-family: monospace;
}

.user-message .message-content :deep(pre),
.user-message .message-content :deep(code) {
  background-color: rgba(255, 255, 255, 0.2);
  color: white;
}
</style> 